package com.ftg.learn.chapter03;

import java.util.Arrays;

/**
 * 案例分析
 *
 * @author 布衣
 */
public class LearnArray02 {

    //  计数器 ： 判断是否存在某一个元素

    /**
     * 判断 数组arr01里面有没有target
     *
     * @param arr01  数组
     * @param target 目标
     * @return true false
     */
    public static boolean exists(int[] arr01, int target) {
        for (int i = 0; i < arr01.length; i++) {
            if (arr01[i] == target) {
                return true;
            }
        }
        return false;
    }

    public static boolean exists01(int[] arr01, int target) {
        for (int i : arr01) {
            if (i == target) {
                return true;
            }
        }
        return false;
    }

    public static boolean exists02(int[] arr01, int target) {
        for (int i = 0, len = arr01.length - 1; i <= len; i++, len--) {
            if (arr01[i] == target || arr01[len] == target) {
                return true;
            }
        }
        return false;
    }

    public static boolean binarySearch(int[] arr02,int target){
        //把一个无序数组转换有序
        Arrays.sort(arr02);
        int left = 0;
        int right = arr02.length - 1;
        while (left < right) {
            int middle = (left + right) >> 1;
            if (middle == 9) {
                return true;
            } else if (middle > 9) {
                right = middle - 1;
            }else{
                left = middle + 1;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        boolean exists = exists(new int[]{1, 2, 3, 31, 24, 56, 2}, 9);
        System.out.println(exists);

        int[] arr01 = new int[]{23, 3, 45, 3, 2};
        int target = 8;
        boolean b = exists01(arr01, target);
        System.out.println(b);

    }

}
